/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 递归
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  let res = [];

  getEveryLevel(root, 0, res);
  return res;
};

function getEveryLevel(root, index, res) {
  if (root === null) return;

  if (res[index]) {
    res[index].push(root.val);
  } else {
    res[index] = [root.val];
  }
  getEveryLevel(root.left, index + 1, res);
  getEveryLevel(root.right, index + 1, res);
}

/**
 * 迭代层序遍历
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  if (root === null) return [];
  let res = [],
    levelArr,
    queue = [root];

  while (queue.length > 0) {
    levelArr = [];
    let len = queue.length,
      node;

    for (let i = 0; i < len; i++) {
      node = queue.shift();
      levelArr.push(node.val);
      node.left && queue.push(node.left);
      node.right && queue.push(node.right);
    }
    res.push(levelArr);
  }

  return res;
};

let a = new TreeNode(1);
a.right = new TreeNode(2);
a.right.left = new TreeNode(3);

console.log(levelOrder(a));
